package com.xcc.dataStructures.demo09_tree;

/**
 * 顺序存储二叉树
 */
public class SeqBinaryTreeDemo {

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 6, 7};
        SeqBinaryTree binaryTree = new SeqBinaryTree(arr);
        System.out.println("前序遍历");
        binaryTree.preOrder();  // 1 2 4 5 3 6 7
        System.out.println("中序遍历");
        binaryTree.midOrder();  // 4 2 5 1 6 3 7
        System.out.println("后续遍历");
        binaryTree.postOrder(); // 4 5 2 6 7 3 1
    }

}

class SeqBinaryTree {

    private int[] arr;

    public SeqBinaryTree(int[] arr) {
        this.arr = arr;
    }

    public void preOrder() {
        this.preOrder(0);
    }

    /**
     * 前序
     */
    public void preOrder(int index) {
        if (arr == null || arr.length == 0) {
            System.out.println("当前数组为空!");
            return;
        }
        System.out.println(arr[index]);
        if ((2 * index + 1) < arr.length) {
            preOrder(2 * index + 1);
        }
        if ((2 * index + 2) < arr.length) {
            preOrder(2 * index + 2);
        }
    }

    public void midOrder() {
        midOrder(0);
    }

    /**
     * 中序
     */
    public void midOrder(int index) {
        if (arr == null || arr.length == 0) {
            System.out.println("当前数组为空!");
            return;
        }
        if ((2 * index + 1) < arr.length) {
            midOrder(2 * index + 1);
        }
        System.out.println(arr[index]);
        if ((2 * index + 2) < arr.length) {
            midOrder(2 * index + 2);
        }
    }

    public void postOrder() {
        this.postOrder(0);
    }

    /**
     * 后序遍历
     */
    public void postOrder(int index) {
        if (arr == null || arr.length == 0) {
            System.out.println("当前数组为空!");
            return;
        }
        if ((2 * index + 1) < arr.length) {
            postOrder(2 * index + 1);
        }
        if ((2 * index + 2) < arr.length) {
            postOrder(2 * index + 2);
        }
        System.out.println(arr[index]);
    }
}
